const AJAX = require("../common/request")
const API = require("./api")

// 检查登录状态
function checkLogin() {
	return new Promise((resolve, reject) => {
		if (wx.getStorageSync('wxLoginStatus')) {
			return resolve(true)
		}
		wx.login({
			success: (resLogin) => {
				// 调用接口传参code,检查当前用户openid是否已经注册过
				AJAX.GET("/wxLogin/getOpenId", {
					code: resLogin.code
				}).then(res => {
					wx.setStorageSync('wxLoginOpenid', res.openId)
					wx.setStorageSync('wechatUserId', res.wechatUser.wechatUserId)
					wx.setStorageSync('wxUserId', res.wechatUser.wechatUserId)
					App.globalData.user.wxLoginOpenid = res.openId
					App.globalData.user.wxUserId = res.wechatUser.wechatUserId
					App.globalData.user.wechatUserId = res.wechatUser.wechatUserId




					// 0、老用户无需进行注册 1、新用户需要注册
					if (res.status === 0) {
						// 注册过直接存储openid与用户头像用户昵称信息
						wx.setStorageSync('wxLoginUsername', res.wechatUser.wechatUserName)
						wx.setStorageSync('wxLoginImg', res.wechatUser.headImg)
						wx.setStorageSync('wxLoginPhone', res.wechatUser.phone)
						wx.setStorageSync('wxLoginStatus', true) // 登录状态
						App.globalData.user.wxLoginUsername = res.wechatUser.wechatUserName
						App.globalData.user.wxLoginStatus = true
						App.globalData.user.wxLoginPhone = res.wechatUser.phone
						App.globalData.user.wxLoginImg = res.wechatUser.headImg
						return resolve(true)
					} else {
						wx.showModal({
							title: '提示',
							content: '当前尚未登录，请问是否前往快速登录',
							complete: (res) => {
								if (res.cancel) {
									return resolve(false)
								}
								if (res.confirm) {
									// 未注册过跳转注册页面进行注册
									wx.navigateTo({
										url: '/pages/login/index',
									})
									return resolve(false)
								}
							}
						})

						return resolve(false)
					}
				}).catch(err => {
					console.error("登录接口返回错误checkLogin", err)
					return reject(false)
				})
			}
		})
	})
}

// 使用方法debounced,throttle
// leeBtnClick: throttle(function (params) {
//   console.log(this,params)
//   console.log("执行需要触发事件得函数方法")
// }, 3000),

/**
 * 防抖函数
 * 1、N秒内的多次触发仅执行最后一次
 * 2、在不断的触发事件时以最后一次触发为*标准*准进行调用执行
 * 3、判断连续触发事件的标准为(N秒内触发则重新计算时间直至取最后一次)
 * @param fn 需要防抖处理的回调函数
 * @param delay 防抖处理的延迟标准时间
 * @param immediate 是否默认 立即执行(去除延迟时间影响)
 */
function debounced(fn, delay = 1000, immediate = false) {
	let timer = null
	return function () {
		if (immediate) {
			console.log("立即执行参数 执行一次方法")
			fn.apply(this, arguments)
			immediate = false
			return
		}
		if (timer) {
			console.log("当前正在重复点击，准备重置时间，重新计算后等待N秒触发最后一次事件执行")
			clearTimeout(timer)
		}
		timer = setTimeout(() => {
			console.log("进入类启用定时器防抖执行了一次方法咯！！！")
			clearTimeout(timer)
			fn.apply(this, arguments)
		}, delay)
	}
}

/**
 * 节流函数
 * N秒内仅执行第一次
 * @param fn 需要节流处理的回调函数
 * @param delay 节流处理的延迟标准时间
 * @param immediate 是否默认 立即执行(去除延迟时间影响)
 */
function throttle(fn, delay = 1000, immediate = false) {
	let timer
	let status = false // 是否为重复点击状态
	return function () {
		let _this = this
		let args = arguments

		if (immediate) {
			fn.apply(_this, args)
			immediate = false
			return
		}
		if (status) {
			wx.showToast({
				title: '请勿重复点击',
				icon: "none"
			})
			return
		}
		fn.apply(_this, args)
		status = true // 修改状态
		timer = setTimeout(() => {
			status = false
		}, delay)
	}
}

function addDomainToImageUrls(htmlString, domain) {
	return htmlString.replace(/(<img[^>]+src=")([^"]+")/g, function (match, p1, p2) {
		console.log("-- : ",match,p1,p2)
		if(p2.indexOf("data:")>=0){
			return p1 + p2
		}
		return p1 + domain + p2;
	});
}

// date格式化
function formatTime(date, rule) {
	var year = date.getFullYear()
	var month = date.getMonth() + 1
	var day = date.getDate()

	var hour = date.getHours()
	var minute = date.getMinutes()
	var second = date.getSeconds()

	if (rule == "YYYY-MM-DD") {
		return [year, month, day].map(formatNumber).join('-')
	} else if (rule == "hh:mm:ss") {
		return [hour, minute, second].map(formatNumber).join(':')
	} else {
		return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
	}
}


function formatNumber(n) {
	n = n.toString()
	return n[1] ? n : '0' + n
}


/**
 * 获取小程序发布状态
 * dev 开发/prod 生产
 */
function getAppLetStatus() {
	return new Promise((resolve, reject) => {
		// 取
		wx.request({
			url: API.BASEURL + "/system/AppWechat/getAppStatus",
			data: "",
			method: "POST",
			header: {
				'content-type': 'application/json', // 默认值
			},
			dataType: "json",
			timeout: 6000,
			success(res) {
				let result = res.data.data || "prod"
				// 存
				console.warn("小程序发布状态", result)
				wx.setStorageSync('APPLETSTATUS', result)
				resolve(result)
			},
			fail(err) {
				console.error("公用错误", err)
				wx.setStorageSync('APPLETSTATUS', "prod")
				AJAX.alertErr(err)
			},
			complete(com) {
				// console.warn(com)
				wx.hideLoading()
			}
		})
	})
}
function generateUUID() {
	var d = new Date().getTime(); //Timestamp
	var d2 = (performance && performance.now && (performance.now()*1000)) || 0; //Time in microseconds since page-load or 0 if unsupported
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
		var r = Math.random() * 16; //random number between 0 and 16
		if(d > 0) { //Use timestamp until depleted
			r = (d + r)%16 | 0;
			d = Math.floor(d/16);
		} else { //Use microseconds since page-load if supported
			r = (d2 + r)%16 | 0;
			d2 = Math.floor(d2/16);
		}
		return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
	});
}

export {
	checkLogin,
	debounced,
	throttle,
	addDomainToImageUrls,
	formatTime,
	getAppLetStatus,
	generateUUID
}